import React from 'react';
import gql from 'graphql-tag';
import {connect} from 'react-apollo';
import {Table, Icon, Tag} from 'antd';
import TableBase from './table';
import g from '../../global';

const columns = [{
    width: 250,
    key: 'name',
    title: '名称',
    dataIndex: 'name'
}, {
    width: 100,
    key: 'type',
    title: '类型',
    dataIndex: 'type'
}, {
    width: 60,
    key: 'length',
    title: '长度',
    dataIndex: 'length',
    className: 'right'
}, {
    width: 60,
    key: 'not_null',
    title: '非空',
    dataIndex: 'not_null',
    className: 'center',
    render: text => {
        if (text) {
            return <Icon type="check" className="green bold"/>;
        }
        return <span/>;
    }
}, {
    width: 60,
    key: 'key',
    title: '键值',
    dataIndex: 'key',
    className: 'center',
    render: (value, row) => {
        if (value) {
            return <Tag color="blue">主</Tag>;
        }
        if (row.unique) {
            return <Tag color="green">一</Tag>;
        }
        return <span/>;
    }
}, {
    key: 'values',
    title: '范围',
    dataIndex: 'values',
    render: text => {
        if (Array.isArray(text)) {
            text = text.join(', '); // 加空格为了换行
        }
        return <span>{text || ''}</span>;
    }
}, {
    width: 200,
    key: 'default',
    title: '默认',
    dataIndex: 'default'
}];

const mapQueriesToProps = ({ownProps: props}) => ({
    data: {
        query: gql`
            query get($connection: String!, $database: String!, $table: String!) {
                fields(connection: $connection, database: $database, table: $table) {
                    name, type, length, not_null, key, values, default
                }
            }
        `,
        variables: {
            connection: props.params.conn,
            database: props.params.db,
            table: props.params.table
        }
    }
});

@connect({mapQueriesToProps})
export default class Field extends TableBase {
    state = {height: undefined};

    init() {
        this.data = 'fields';
    }

    done(data) {
        return (
            <Table
                size="middle" bordered
                rowClassName={g.tableRowClass}
                columns={columns} dataSource={data}
                rowKey={row => row.name} pagination={false}
                scroll={{y: this.state.height}}
            />
        );
    }
}
